package us.mooresr.aircraftscheduling.client;

import com.google.gwt.event.shared.EventBus;
import com.google.inject.Inject;
import com.google.inject.Singleton;

import us.mooresr.aircraftscheduling.client.events.UserLoggedInEvent;
import us.mooresr.aircraftscheduling.client.events.UserLoggedInEventHandler;
import us.mooresr.aircraftscheduling.client.events.UserLoggedOutEvent;
import us.mooresr.aircraftscheduling.client.events.UserLoggedOutEvent.UserLoggedOutHandler;
import us.mooresr.aircraftscheduling.shared.model.User;
import us.mooresr.aircraftscheduling.shared.model.UserDetail;

@Singleton
public class LoginStateManager {
	private UserDetail currentUserDetail;
	private EventBus eventBus;
	
	@Inject
	public LoginStateManager(EventBus eventBus) {
		
		this.eventBus = eventBus;
		
		this.eventBus.addHandler(UserLoggedInEvent.getType(), new UserLoggedInEventHandler() {

			@Override
			public void onLogin(UserLoggedInEvent event) {
				currentUserDetail = event.getUserDetail();	
				
			}
			
		});
		
		this.eventBus.addHandler(UserLoggedOutEvent.getType(), new UserLoggedOutHandler() {

			@Override
			public void onUserLoggedOut(UserLoggedOutEvent event) {
				currentUserDetail = null;
				
			}
			
		});
		
	}
	
	public Boolean isLoggedIn() {
		if (currentUserDetail == null) {
			return false;
		} else {
			return true;
		}
	}
	
	public Boolean isAdmin() {
		if (currentUserDetail == null) {
			return false;
		} else {
			if (currentUserDetail.getIsAdmin() == true) {
				return true;
			} else {
				return false;
			}
		}
	}
	
	public Long getCurrentUserId() {
		if (currentUserDetail == null) {
			return null;
		} else {
			return currentUserDetail.getId();
		}
	}
	
	public Boolean canEdit(User user) {
		if (currentUserDetail.getIsAdmin()) {
			return true;
		} else {
			if (currentUserDetail.getId().equals(user.getUserId())) {
				return true;
			} else {
				return false;
			}
		}
	}
	
	public String getCurrentUserName() {
		if (currentUserDetail == null) {
			return null;
		} else {
			return currentUserDetail.getName();		
		}
	}

}
